package gihub.hanlyjiang.hanlygithub.user;

import android.app.Activity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.TextView;

import butterknife.BindView;
import gihub.hanlyjiang.hanlygithub.AppConstant;
import gihub.hanlyjiang.hanlygithub.R;
import gihub.hanlyjiang.hanlygithub.base.BKBaseFragment;
import gihub.hanlyjiang.hanlygithub.service.OSCRequestor;
import gihub.hanlyjiang.hanlygithub.service.OSCUserInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 用户信息展示界面
 *
 * @author hanlyjiang on 2017/6/21-21:24.
 * @version 1.0
 */

public class UserLoginFragment extends BKBaseFragment implements Callback<UserResponse>, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.tv_userinfo)
    TextView userInfo;

    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefreshLayout;

    private OSCUserInterface userInterface;
    private OSCRequestor oscRequestor;
    private Call<UserResponse> userResponseCall;


    @Override
    public int getLayoutResId() {
        return R.layout.fragment_user_login;
    }


    @Override
    public void initUI(View rootView, Activity activity) {
        userInfo.setText("正在获取用户信息...");
        swipeRefreshLayout.setRefreshing(true);
        swipeRefreshLayout.setOnRefreshListener(this);

        oscRequestor = new OSCRequestor();
        userInterface = oscRequestor.newUserService();

        userResponseCall = userInterface.getUserInfo("hanlyjiang", AppConstant.ACCESS_TOKEN);
        userResponseCall.enqueue(this);

    }

    @Override
    public void refreshUI() {
        swipeRefreshLayout.setRefreshing(true);
        userResponseCall.clone().enqueue(this);
    }

    @Override
    public void onResponse(Call<UserResponse> call, final Response<UserResponse> response) {
        if (response.code() == 200) {
            userInfo.setText(response.body().toString());
        } else {
            userInfo.setText("请求失败");
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onFailure(Call<UserResponse> call, Throwable t) {
        swipeRefreshLayout.setRefreshing(false);
        userInfo.setText("请求失败");
    }

    @Override
    public void onRefresh() {
        userInfo.setText("正在获取用户信息...");
        refreshUI();
    }
}
